<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标签名称" prop="tagName">
        <el-input
          v-model="queryParams.tagName"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签类型" prop="tagType">
        <el-select v-model="queryParams.tagType" placeholder="请选择标签类型" clearable>
          <el-option label="文本" value="0" />
          <el-option label="数字" value="1" />
          <el-option label="选择" value="2" />
          <el-option label="是否" value="3" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tags:manage:add']"
        >添加标签</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tags:manage:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-if="false" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tagList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标签名" align="center" prop="tagName" />
      <el-table-column label="标签类型" align="center" prop="tagType">
        <template slot-scope="scope">
          <el-tag :type="getTagTypeStyle(scope.row.tagType)">
            {{ getTagTypeText(scope.row.tagType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="tagUnit" />
      <el-table-column label="标签可选值" align="center" prop="tagOptions" />
      <el-table-column label="是否需要审核" align="center" prop="isApply">
        <template slot-scope="scope">
          <!--       <el-switch
            v-model="scope.row.isApply"
            :active-value="1"
            :inactive-value="0"
            active-text=""
            inactive-text=""
            disabled
          />-->
          <span>{{ scope.row.isApply === 1 ? '需要' : '不需要' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="可见权限" align="center" prop="visibleRange" /> -->
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tags:manage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tags:manage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改标签对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="860px" append-to-body custom-class="tag-manage-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" style="width: 20rem;"/>
        </el-form-item>
        <el-form-item label="标签类型" prop="tagType">
          <el-select v-model="form.tagType" placeholder="请选择标签类型" @change="handleTagTypeChange" style="width: 20rem;">
            <el-option label="文本" value="0" />
            <el-option label="数字" value="1" />
            <el-option label="选择" value="2" />
            <el-option label="是否" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签单位" prop="tagUnit" v-if="form.tagType === '1'">
          <el-input v-model="form.tagUnit" placeholder="请输入标签单位" style="width: 20rem;"/>
        </el-form-item>
        <el-form-item label="标签选项" prop="tagOptions" v-if="form.tagType === '2'">
          <el-input v-model="form.tagOptions" type="textarea" placeholder="请输入标签选项，多个选项用英文逗号分隔" style="width: 20rem;"/>
        </el-form-item>
        <el-form-item label="是否需要审核" prop="isApply">
          <el-switch
            v-model="form.isApply"
            :active-value="1"
            :inactive-value="0"
            active-text="需要"
            inactive-text="不需要"
          />
        </el-form-item>
      <el-card shadow="never" body-style="padding: 8px 12px;">
          <el-tabs v-model="activeVisibilityTab">
            <el-tab-pane label="游客" name="tourist">
              <div style="padding: 6px 4px;">
                <el-checkbox v-model="visibility.touristVisible">游客可见</el-checkbox>
              </div>
            </el-tab-pane>
            <el-tab-pane label="企业用户" name="company">
              <div style="padding: 6px 0;">
                <!-- 搜索表单 -->
                <el-form :model="companyTableQueryParams" ref="companyTableQueryForm" size="small" :inline="true" label-width="80px" style="margin-bottom: 10px;">
                  <el-form-item label="企业名称" prop="companyName">
                    <el-input
                      v-model="companyTableQueryParams.companyName"
                      placeholder="请输入企业名称"
                      clearable
                      @keyup.enter.native="handleCompanyQuery"
                      style="width: 200px;"
                    />
                  </el-form-item>
                  <el-form-item label="企业类型" prop="companyTypeId">
                    <el-select v-model="companyTableQueryParams.companyTypeId" placeholder="请选择企业类型" clearable style="width: 200px;">
                      <el-option
                        v-for="dict in dict.type.company_type"
                        :key="dict.companyTypeId"
                        :label="dict.companyType"
                        :value="dict.companyTypeId"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleCompanyQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="handleCompanyReset">重置</el-button>
                  </el-form-item>
                </el-form>
                <el-table
                  ref="companyTable"
                  v-loading="companyTableLoading"
                  :data="companyTableList"
                  @selection-change="handleCompanySelectionChange"
                  :row-key="getCompanyRowKey"
                  max-height="400"
                  style="width: 100%;"
                >
                  <el-table-column type="selection" width="75" align="center" :reserve-selection="true" /> 
                  <el-table-column label="企业名称" align="center" prop="companyName" show-overflow-tooltip />
                  <el-table-column label="联系人" width="150" align="center" prop="contact" show-overflow-tooltip />
                  <el-table-column label="联系电话" width="150" align="center" prop="contactPhone" show-overflow-tooltip />
                </el-table>
                <pagination
                  v-show="companyTableTotal > 0"
                  :total="companyTableTotal"
                  :page.sync="companyTableQueryParams.current"
                  :limit.sync="companyTableQueryParams.size"
                  :page-sizes="[100, 150, 200, 250]"
                  @pagination="getCompanyTableList"
                  style="margin-top: 10px;"
                />
              </div>
            </el-tab-pane>
            <el-tab-pane label="职能部门及联企用户" name="dept_branch">
              <div style="padding: 6px 0;">
                <el-tree
                  ref="deptUserTree"
                  :data="deptBranchTree"
                  node-key="key"
                  show-checkbox
                  :default-checked-keys="visibility.checkedDeptBranchKeys"
                  :props="treeProps"
                  style="max-height: 320px; overflow: auto; width: 36rem;"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <i v-if="data.type==='dept'" class="el-icon-office-building" style="color:#409EFF;margin-right:6px;"></i>
                    <i v-else-if="data.type==='user'" class="el-icon-user" style="color:#67C23A;margin-right:6px;"></i>
                    <i v-else class="el-icon-menu" style="color:#909399;margin-right:6px;"></i>
                    <span>{{ node.label }}</span>
                  </span>
                </el-tree>
                <div style="margin-top: 6px;">
                  <el-button size="mini" @click="checkAllTree">全选</el-button>
                  <el-button size="mini" @click="uncheckAllTree">清空</el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageTag, saveTag, deleteCompanyTagCore, getTag, updateTag, companyTypeList, getTagVisibleRange } from "@/api/biz/api";

export default {
  name: "TagManage",
  dicts: ['common_status', 'audit_status', 'company_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标签表格数据
      tagList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        tagName: null,
        tagType: null,
        // status: null
      },
      // 表单参数
      form: {},
      // 可见性 Tab
      activeVisibilityTab: 'tourist',
      // 可见性相关数据
      visibility: {
        touristVisible: false,
        selectedCompanyIds: [],
        checkedDeptBranchKeys: [],
        //以下3个都是{name:'',type:''}格式
        selectedCompanyNames:[

        ],
        selectedBranchNames:[

        ],
        selectedBranchMemberNames:[

        ],

      },
      companyOptions: [],
      deptBranchTree: [],
      treeProps: { children: 'children', label: 'label' },
      // 企业表格相关数据
      companyTableList: [], // 当前页显示的数据
      companyTableAllList: [], // 所有企业数据（从接口一次性获取）
      companyTableTotal: 0,
      companyTableLoading: false,
      companyTableQueryParams: {
        current: 1,
        size: 100,
        companyName: null,
        companyTypeId: null,
      },
      // 表单校验
      rules: {
        tagName: [
          { required: true, message: "标签名称不能为空", trigger: "blur" }
        ],
        tagType: [
          { required: true, message: "请选择标签类型", trigger: "change" }
        ],
        tagUnit: [
          {
            validator: (rule, value, callback) => {
              if (this.form.tagType === '1' && (!value || value.trim() === '')) {
                callback(new Error('数字类型标签的单位不能为空'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        tagOptions: [
          {
            validator: (rule, value, callback) => {
              if (this.form.tagType === '2' && (!value || value.trim() === '')) {
                callback(new Error('选择类型标签的选项不能为空'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        showModel: [
          { required: true, message: "请选择标签可见性", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听 tab 切换，当切换到企业用户 tab 时进行前端分页
    activeVisibilityTab(newVal) {
      if (newVal === 'company') {
        this.handleCompanyQuery();
      }
    }
  },
  methods: {
    /** 获取企业表格列表（前端分页） */
    getCompanyTableList() {
      this.companyTableLoading = true;
      
      // 从所有数据中筛选
      let filteredList = [...this.companyTableAllList];
      
      // 按企业名称筛选
      if (this.companyTableQueryParams.companyName) {
        const keyword = this.companyTableQueryParams.companyName.toLowerCase();
        filteredList = filteredList.filter(item => 
          item.companyName && item.companyName.toLowerCase().includes(keyword)
        );
      }
      
      // 按企业类型筛选
      if (this.companyTableQueryParams.companyTypeId) {
        filteredList = filteredList.filter(item => 
          item.companyTypeId == this.companyTableQueryParams.companyTypeId
        );
      }
      
      // 计算总数
      this.companyTableTotal = filteredList.length;
      
      // 前端分页
      const start = (this.companyTableQueryParams.current - 1) * this.companyTableQueryParams.size;
      const end = start + this.companyTableQueryParams.size;
      this.companyTableList = filteredList.slice(start, end);
      
      this.companyTableLoading = false;
      
      // 恢复已选中的行
      this.$nextTick(() => {
        this.restoreCompanySelection();
      });
    },
    /** 企业表格行key */
    getCompanyRowKey(row) {
      return row.id || row.companyId;
    },
    /** 企业表格选择变化处理 */
    handleCompanySelectionChange(selection) {
      this.visibility.selectedCompanyIds = selection.map(item => item.memberId);
    },
    /** 企业表格搜索 */
    handleCompanyQuery() {
      this.companyTableQueryParams.current = 1;
      this.getCompanyTableList();
    },
    /** 企业表格重置 */
    handleCompanyReset() {
      this.companyTableQueryParams.companyName = null;
      this.companyTableQueryParams.companyTypeId = null;
      this.companyTableQueryParams.current = 1;
      this.$refs.companyTableQueryForm && this.$refs.companyTableQueryForm.resetFields();
      this.getCompanyTableList();
    },
    /** 获取标签可见范围数据（统一接口） */
    async getTagVisibleRangeData(tagId = 0) {
      try {
        // 如果是新增，tagId传0，接口会返回所有可选数据
        const response = await getTagVisibleRange(tagId);

        if (response.code === 200 && response.data) {
          const data = response.data;
          
          // 游客可见性 - r100.visible (支持大小写)
          const r100 = data.R100;
          this.visibility.touristVisible = r100?.visible || false;
          
          // 企业用户数据（一次性返回，需要前端分页）- r101.companyCores (支持大小写)
          const r101 = data.R101;
          const companyCores = r101?.companyCores || [];
          this.companyTableAllList = companyCores;
          
          // 根据 tagVisible 设置已选中的企业ID
          this.visibility.selectedCompanyIds = companyCores
            .filter(item => item.tagVisible === true)
            .map(item => item.memberId);
          
          // 初始化企业表格数据
          this.companyTableQueryParams.current = 1;
          this.getCompanyTableList();
          
          // 职能部门及联企用户数据（树状结构）- r102 (支持大小写)
          const r102 = data.R102;
          const sysDepts = r102?.sysDepts || [];
          const branchMembers = r102?.branchMembers || [];
          // 构建树状结构
          this.deptBranchTree = this.buildDeptBranchTree(sysDepts, branchMembers);
          console.log('构建后的树状结构:', this.deptBranchTree);
          
          // 根据 tagVisible 设置已选中的节点keys
          const checkedKeys = [];
          
          // 递归收集选中的节点keys（包括部门和联企用户）
          const collectCheckedNodes = (nodes) => {
            nodes.forEach(node => {
              if (node.tagVisible === true) {
                checkedKeys.push(node.key);
              }
              if (node.children && node.children.length > 0) {
                collectCheckedNodes(node.children);
              }
            });
          };
          collectCheckedNodes(this.deptBranchTree);
          
          this.visibility.checkedDeptBranchKeys = checkedKeys;
          
          // 设置树节点的选中状态
          this.$nextTick(() => {
            if (this.$refs.deptUserTree) {
              if (checkedKeys.length > 0) {
                this.$refs.deptUserTree.setCheckedKeys(checkedKeys);
              } else {
                // 即使没有选中的节点，也要设置空数组，确保树能正常显示
                this.$refs.deptUserTree.setCheckedKeys([]);
              }
            }
          });
        } else {
          console.warn('接口返回数据格式不正确:', response);
        }
      } catch (error) {
        console.error('获取标签可见范围失败:', error);
        // 初始化默认值
        this.visibility.touristVisible = false;
        this.companyTableAllList = [];
        this.deptBranchTree = [];
        this.visibility.checkedDeptBranchKeys = [];
        this.visibility.selectedCompanyIds = [];
      }
    },
    /** 构建部门及联企用户树状结构 */
    buildDeptBranchTree(sysDepts, branchMembers) {
      // 创建部门映射表
      const deptMap = {};
      sysDepts.forEach(dept => {
        deptMap[dept.deptId] = {
          key: `dept_${dept.deptId}`,
          type: 'dept',
          label: dept.deptName,
          deptId: dept.deptId,
          parentId: dept.parentId,
          tagVisible: dept.tagVisible || false,
          originalData: dept,
          children: []
        };
      });
      
      // 构建部门树
      const deptTree = [];
      Object.values(deptMap).forEach(node => {
        const pid = node.parentId;
        if (pid && deptMap[pid]) {
          deptMap[pid].children.push(node);
        } else {
          deptTree.push(node);
        }
      });
      
      // 将联企用户挂到对应部门下
      branchMembers.forEach(member => {
        const userNode = {
          key: `user_${member.memberId}`,
          type: 'user',
          label: member.memberName || '联企用户',
          memberId: member.memberId,
          branchId: member.branchId,
          tagVisible: member.tagVisible || false,
          originalData: member,
          children: []
        };
        
        // 如果 branchId 存在且对应部门存在，挂到该部门下
        if (member.branchId && deptMap[member.branchId]) {
          deptMap[member.branchId].children.push(userNode);
        } else {
          // 如果 branchId 不存在或对应部门不存在，创建一个虚拟根节点
          // 或者挂到根节点下（这里选择挂到根节点）
          // 可以创建一个"联企用户"虚拟节点，或者直接挂到根节点
          // 为了保持结构清晰，创建一个虚拟根节点
          let branchRoot = deptTree.find(node => node.key === 'branch_root');
          if (!branchRoot) {
            branchRoot = {
              key: 'branch_root',
              type: 'group',
              label: '联企用户',
              children: []
            };
            deptTree.push(branchRoot);
          }
          branchRoot.children.push(userNode);
        }
      });
      
      return deptTree;
    },
    /** 查询企业类型列表 */
    getCompanyTypeList() {
      return companyTypeList().then(response => {
        if (response.code === 200) {
          // 将企业类型数据转换为字典格式
          const typeData = response.data || [];
          this.dict.type.company_type = typeData.map(item => ({
            companyTypeId: item.id,
            companyType: item.typeName,
            label: item.typeName,
            value: item.id
          }));
        }
        return response;
      }).catch(error => {
        console.error('获取企业类型列表失败:', error);
        this.dict.type.company_type = [];
        return Promise.reject(error);
      });
    },
    /** 恢复企业表格选中状态 */
    restoreCompanySelection() {
      if (this.$refs.companyTable && this.visibility.selectedCompanyIds.length > 0) {
        this.companyTableList.forEach(row => {
          const rowId = row.memberId;
          // 确保类型一致进行比较
          const selectedIds = this.visibility.selectedCompanyIds.map(id => String(id));
          if (selectedIds.includes(String(rowId))) {
            this.$refs.companyTable.toggleRowSelection(row, true);
          }
        });
      }
    },
    checkAllTree() {
      const keys = [];
      const walk = (nodes) => {
        (nodes || []).forEach(n => { keys.push(n.key); if (n.children && n.children.length) walk(n.children); });
      };
      walk(this.deptBranchTree);
      this.$refs.deptUserTree && this.$refs.deptUserTree.setCheckedKeys(keys);
      this.visibility.checkedDeptBranchKeys = keys;
    },
    uncheckAllTree() {
      this.$refs.deptUserTree && this.$refs.deptUserTree.setCheckedKeys([]);
      this.visibility.checkedDeptBranchKeys = [];
    },
    /** 获取标签类型文本 */
    getTagTypeText(tagType) {
      const typeMap = {
        0: '文本',
        1: '数字',
        2: '选择',
        3: '是否'
      };
      return typeMap[tagType] || '未知';
    },
    /** 获取标签类型样式 */
    getTagTypeStyle(tagType) {
      const styleMap = {
        0: 'primary',   // 文本 - 蓝色
        1: 'success',   // 数字 - 绿色
        2: 'warning',   // 选择 - 橙色
        3: 'danger'     // 是否 - 红色
      };
      return styleMap[tagType] || '';
    },
    /** 标签类型变化处理 */
    handleTagTypeChange(value) {
      // 当标签类型改变时，清空相关字段
      if (value !== '1') {
        this.form.tagUnit = null;
      }
      if (value !== '2') {
        this.form.tagOptions = null;
      }
      // 清除相关字段的验证错误
      this.$nextTick(() => {
        this.$refs.form.clearValidate(['tagUnit', 'tagOptions']);
      });
    },
    /** 查询标签列表 */
    getList() {
      this.loading = true;
      pageTag(this.queryParams).then(response => {
        console.log('标签列表数据:', response);
        this.tagList = response.data?.records || [];
        this.total = response.data?.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取标签列表失败:', error);
        this.tagList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    // 发送消息
    handleSendMessage() {
      this.$modal.msg('TODO: 发送消息');
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tagName: null,
        tagType: null,
        tagUnit: null,
        tagOptions: null,
        showModel: 0, // 可见权限：暂时默认0
        isApply: 0, // 0 不需要；1 需要
        visible: 'R100', // 可见范围：R100-游客，R101-企业，R102-职能部门和联企人员
        // sort: 0
      };
      this.activeVisibilityTab = 'tourist';
      this.visibility = {
        touristVisible: false,
        selectedCompanyIds: [],
        checkedDeptBranchKeys: []
      };
      // 重置企业表格
      this.companyTableQueryParams = {
        current: 1,
        size: 100,
        companyName: null,
        companyTypeId: null,
      };
      this.companyTableList = [];
      this.companyTableAllList = [];
      this.companyTableTotal = 0;
      if (this.$refs.companyTable) {
        this.$refs.companyTable.clearSelection();
      }
      // 重置树数据
      this.deptBranchTree = [];
      if (this.$refs.deptUserTree) {
        this.$refs.deptUserTree.setCheckedKeys([]);
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加标签";
      // 获取可见性数据（统一接口）
      this.getTagVisibleRangeData(0);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 确保标签类型是字符串格式，以匹配表单选项的value类型
      this.form = {
        ...row,
        tagType: String(row.tagType),
        isApply: row.isApply || 0,
        visible: row.visible || 'R100'
      };

      // 根据visible字段设置对应的tab为选中状态
      const tabMap = {
        'R100': 'tourist',      // 游客的可见范围
        'R101': 'company',      // 企业的可见范围
        'R102': 'dept_branch'   // 职能部门和联企人员的可见范围
      };
      this.activeVisibilityTab = tabMap[row.visible] || 'tourist';

      this.open = true;
      this.title = "修改标签";
      
      // 获取可见性数据（统一接口，传入tagId）
      this.getTagVisibleRangeData(row.id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 构造 visible 对象
          const visible = {};
          
          // R100: 游客可见
          if (this.activeVisibilityTab === 'tourist') {
            visible.R100 = {
              visible: this.visibility.touristVisible || false
            };
          } else {
            visible.R100 = false;
          }
          
          // R101: 企业可见
          if (this.activeVisibilityTab === 'company') {
            visible.R101 = {
              companyMemberIds: this.visibility.selectedCompanyIds || []
            };
          } else {
            visible.R101 = {
              companyMemberIds: []
            };
          }
          
          // R102: 职能部门及联企用户
          if (this.activeVisibilityTab === 'dept_branch') {
            const checkedKeys = this.$refs.deptUserTree ? this.$refs.deptUserTree.getCheckedKeys() : this.visibility.checkedDeptBranchKeys;
            const branchIds = [];
            const branchMemberIds = [];
            
            // 遍历选中的 keys，提取对应的数据
            // 从树结构中查找对应的节点数据
            const findNodeByKey = (nodes, targetKey) => {
              for (const node of nodes) {
                if (node.key === targetKey) {
                  return node;
                }
                if (node.children && node.children.length > 0) {
                  const found = findNodeByKey(node.children, targetKey);
                  if (found) return found;
                }
              }
              return null;
            };
            
            checkedKeys.forEach(key => {
              const node = findNodeByKey(this.deptBranchTree, key);
              if (node) {
                if (node.type === 'dept') {
                  // 部门节点，使用 deptId
                  if (node.deptId) {
                    branchIds.push(node.deptId);
                  }
                } else if (node.type === 'user') {
                  // 联企用户节点，使用 memberId
                  if (node.memberId) {
                    branchMemberIds.push(node.memberId);
                  }
                }
              }
            });
            
            visible.R102 = {
              branchIds: branchIds,
              branchMemberIds: branchMemberIds
            };
          } else {
            visible.R102 = {
              branchIds: [],
              branchMemberIds: []
            };
          }
          
          // 构建提交数据
          const submitData = {
            id: this.form.id || null,
            tagName: this.form.tagName,
            tagType: Number(this.form.tagType), // 确保是数字类型
            tagUnit: this.form.tagUnit || null,
            tagOptions: this.form.tagOptions || null,
            isApply: this.form.isApply === 1 || this.form.isApply === true,
            visible: visible,
            sort: this.form.sort || 0
          };
          
          // 验证必填字段
          if (!submitData.tagName) {
            this.$modal.msgError("标签名称不能为空");
            return;
          }
          if (submitData.tagType === undefined || submitData.tagType === null) {
            this.$modal.msgError("标签类型不能为空");
            return;
          }
          if (!visible || Object.keys(visible).length === 0) {
            this.$modal.msgError("请设置标签可见性");
            return;
          }

          saveTag(submitData).then(response => {
            if(this.form.id != null) {
              this.$modal.msgSuccess("修改成功");
            } else {
              this.$modal.msgSuccess("新增成功");
            }
            this.open = false;
            this.getList();
          }).catch(error => {
            console.error('保存标签失败:', error);
            this.$modal.msgError("保存失败");
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let idsArray = [];

      if (row && row.id) {
        // 单个删除
        idsArray = [row.id];
      } else if (this.ids && this.ids.length > 0) {
        // 批量删除
        idsArray = this.ids;
      } else {
        this.$modal.msgWarning('请选择要删除的数据');
        return;
      }

      const idsText = idsArray.length === 1 ? `编号为"${idsArray[0]}"` : `共${idsArray.length}条`;

      this.$modal.confirm(`是否确认删除标签${idsText}的数据项？`).then(() => {
        console.log('删除参数:', idsArray);
        return deleteCompanyTagCore(idsArray);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((error) => {
        console.error('删除失败:', error);
        this.$modal.msgError("删除失败");
      });
    }
  }
};
</script>

<style>
/* Scoped styles won't affect el-dialog appended to body; use a custom class */
.tag-manage-dialog .el-dialog__body {
  padding: 10px !important;
}
.tag-manage-dialog .el-tabs__content {
  padding: 10px 0 !important;
}
.tag-manage-dialog .el-card {
  border: none !important;
  box-shadow: none !important;
}
</style>
